from flask import request
from wtforms import Form, IntegerField
from wtforms.validators import NumberRange, ValidationError
from wtforms.compat import iteritems

from app.libs.enums import Scope_dict
from app.libs.error_code import ParameterException


class BaseForm(Form):
    def __init__(self):
        data = request.get_json(silent=True)
        # data = request.files.to_dict()
        args = request.args.to_dict()
        super(BaseForm, self).__init__(data=data, **args)

    def validate_for_api(self):
        valid = super(BaseForm, self).validate()
        if not valid:
            raise ParameterException(msg=self.errors)
        return self

    @property
    def errors(self):
        # if self._errors is None:
        #     self._errors = dict((name, f.errors) for name, f in iteritems(self._fields) if f.errors)
        _form_errors = []
        for name, f in iteritems(self._fields):
            if f.errors:
                for item in f.errors:
                    _form_errors.append(item)
        return _form_errors


class SearchForm(BaseForm):
    limit = IntegerField(validators=[NumberRange(min=1, max=100)], default=10)
    page = IntegerField(validators=[NumberRange(min=1)], default=1)


class TimeForm(BaseForm):
    start = IntegerField(default=129361677)
    end = IntegerField(default=2527739277)


class DelForm(BaseForm):
    id = IntegerField()


class IdForm(BaseForm):
    id = IntegerField()


class SwitchForm(BaseForm):
    id = IntegerField()
    switch = IntegerField()

    def __init__(self, g):
        super(SwitchForm, self).__init__()
        # if g.user.scope != Scope_dict[1]:
        #     raise ValidationError('非超管账户不可修改此权限！')
        self.g = g

    def validate_switch(self, field):
        if self.g.user.scope != Scope_dict[1]:
            raise ValidationError('非超管账户不可修改此权限！')
        if field.data == 0:
            field.data = 1
        else:
            field.data = 0


class SwitchAppAuthForm(BaseForm):
    id = IntegerField()
    switch = IntegerField()

    def validate_switch(self, field):
        if field.data == 0:
            field.data = 1
        else:
            field.data = 0
